'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { queryAllMessage } from '@/services/api';
import type { IClientMessage, IPagination, IQueryParams } from '@/interfaces';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function MessageNavItem({
  isLogin,
  translatedFields,
}: {
  isLogin: boolean;
  translatedFields: PrefixedTTranslatedFields<'navbar'>;
}) {
  const [unreadCount, setUnreadCount] = useState(0);

  const queryAllMessageQuery = useQuery(
    ['/messages', {}],
    async (context) => {
      return (await queryAllMessage({
        query: context.queryKey[1] as IQueryParams,
      })) as IPagination<IClientMessage>;
    },
    {
      enabled: isLogin,
    },
  );

  useEffect(() => {
    const data = queryAllMessageQuery.data;
    if (data) {
      setUnreadCount(calculateUnreadCount(data));
    }
  }, [queryAllMessageQuery.data]);

  function calculateUnreadCount(data: IPagination<IClientMessage>) {
    return (
      data.content.filter((item) => !item.messageRange && !item.state).length +
      data.content.filter((item) => item.state === 'UNREAD').length
    );
  }

  return (
    <>
      {isLogin && (
        <li className="nav-item">
          <Link
            href="/message"
            className="nav-link cursor-pointer d-flex align-items-center"
          >
            <span className="position-relative">
              {translatedFields.message}
              {unreadCount > 0 && (
                <span className="position-absolute top-0 start-100 translate-middle p-1 bg-danger border border-light rounded-circle">
                  <span className="visually-hidden">{unreadCount}</span>
                </span>
              )}
            </span>
          </Link>
        </li>
      )}
    </>
  );
}
